package com.d404.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;
import com.d404.server.GetGroup.Download.Group;
import com.d404.server.GetGroup.Download.Group.Friend;

import helpers.BeanHelper;
import im.beans.Group_User;
import im.beans.User;
import manager.PersistentManager;

/**
 * TODO 未经过验证 TODO 逻辑有问题 Servlet implementation class GetGroup
 */
// @WebServlet("/GetGroup")
public class GetGroup extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetGroup() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// response.getWriter().append("Served at:
		// ").append(request.getContextPath());

		request.setCharacterEncoding("UTF-8");

		String data = request.getParameter("data");
		Upload upload = JSON.parseObject(data, Upload.class);

		Download download = new Download();
		download.setGroups(new ArrayList<Group>());

		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
//		Session session = sf.openSession();
		Session session = sf.getCurrentSession();
		Transaction tx = session.beginTransaction();
		try {
			// 获取最后一次获取群组的时间
			User u = (User) session.get(User.class, upload.getUserID());
			long timestamp = u.getTimestamp();
			// 获取最后一次获取群组之后的群组信息
			Query q = session.createQuery("from Group_User gu where gu.createGroupUserTimestamp > ?");
			q.setParameter(0, timestamp);
			List<Group_User> gus = q.list();
			for (Group_User gu : gus) {
				// 被拉入群组信息
				im.beans.Group gTmep = gu.getGroup();
				Group gBack = new Group();
				gBack.setCrateTime(gTmep.getCreateTime() + "");
				gBack.setGroupID(gTmep.getId());
				gBack.setGroupName(gTmep.getGroupName());
				gBack.setOwnerID(gTmep.getOwnerID() + "");
				gBack.setOwnerName(gTmep.getOwnerName());
				gBack.setFriends(new ArrayList<Friend>());

				// 获取群组中的用户
				Query qUsers = session.createQuery("from Group_User gu where gu.group = ?");
				qUsers.setParameter(0, gTmep);
				List<Group_User> users = qUsers.list();
				for (Group_User guTemp : users) {
					User uTemp = guTemp.getUser();
					Friend f = new Friend();
					f.setFriendID(uTemp.getId());
					f.setFriendName(uTemp.getAccount());
					f.setRealName(guTemp.getRealName());
					// 添加群组用户
					gBack.getFriends().add(f);
				}
				gBack.setUserCount(users.size());
				// 添加群组
				download.getGroups().add(gBack);
			}
			session.getTransaction().commit();
			download.setStatus(Download.SUCCESS);

		} catch (Exception e) {
			tx.rollback();
			download.setStatus(Download.FAILED);
			e.printStackTrace();
		} finally {
//			session.close();
		}

		// 去除空格
		for (Group g : download.getGroups()) {
			for (Friend f : g.getFriends()) {
				try {
					BeanHelper.beanAttributeValueTrim(f);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		System.out.println(JSON.toJSONString(download));
		response.setCharacterEncoding("UTF-8");
		response.getWriter().append(JSON.toJSONString(download));

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	// 上行数据
	public static class Upload {
		long userID;
		String userName;

		public Upload() {
		}

		public Upload(long userID, String userName) {
			this.userID = userID;
			this.userName = userName;
		}

		public long getUserID() {
			return userID;
		}

		public void setUserID(long userID) {
			this.userID = userID;
		}

		public String getUserName() {
			return userName;
		}

		public void setUserName(String userName) {
			this.userName = userName;
		}
	}

	// 下行数据
	public static class Download {
		public static final int SUCCESS = 1;
		public static final int FAILED = 2;
		int status;
		ArrayList<Group> groups;

		public int getStatus() {
			return status;
		}

		public void setStatus(int status) {
			this.status = status;
		}

		public ArrayList<Group> getGroups() {
			return groups;
		}

		public void setGroups(ArrayList<Group> groups) {
			this.groups = groups;
		}

		// 群组
		public static class Group {
			long groupID;
			String groupName;
			String crateTime;
			String ownerID;
			String ownerName;
			int userCount;
			ArrayList<Friend> friends;

			public long getGroupID() {
				return groupID;
			}

			public void setGroupID(long groupID) {
				this.groupID = groupID;
			}

			public String getGroupName() {
				return groupName;
			}

			public void setGroupName(String groupName) {
				this.groupName = groupName;
			}

			public String getCrateTime() {
				return crateTime;
			}

			public void setCrateTime(String crateTime) {
				this.crateTime = crateTime;
			}

			public String getOwnerID() {
				return ownerID;
			}

			public void setOwnerID(String ownerID) {
				this.ownerID = ownerID;
			}

			public String getOwnerName() {
				return ownerName;
			}

			public void setOwnerName(String ownerName) {
				this.ownerName = ownerName;
			}

			public int getUserCount() {
				return userCount;
			}

			public void setUserCount(int userCount) {
				this.userCount = userCount;
			}

			public ArrayList<Friend> getFriends() {
				return friends;
			}

			public void setFriends(ArrayList<Friend> friends) {
				this.friends = friends;
			}

			// 好友
			public static class Friend {
				long friendID;
				String friendName;
				String realName;

				public long getFriendID() {
					return friendID;
				}

				public void setFriendID(long friendID) {
					this.friendID = friendID;
				}

				public String getFriendName() {
					return friendName;
				}

				public void setFriendName(String friendName) {
					this.friendName = friendName;
				}

				public String getRealName() {
					return realName;
				}

				public void setRealName(String realName) {
					this.realName = realName;
				}
			}
		}
	}

}
